package com.byq.mm.common.engine.listener.filter;


import com.byq.mm.common.engine.Environment;

import java.util.HashMap;
import java.util.Map;

import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Stanza;


public class MessageFilter extends AbstractFilter{

	public MessageFilter(AbstractFilter n, Environment e) {
		super(n, e);

	}
	


	@Override
	protected boolean filt(Stanza data) {
		if(data instanceof Message)
			return true;
		return false;
	}


	@Override
	protected void myprocess(Stanza data ) {
		processPacket(data);

	}
	public void processPacket(Stanza packet) {

		Message msg = (Message) packet;
		Map<String, String> mi = getMessageInfo(msg);
		env.getLiteStore().queueIncomingMessage(mi);
//		Map<String, String> msgInfo = env.getLiteStore().getMessageInfo(msg);

//		env.getLiteStore().queueIncomingMessage(msgInfo);

//		env.getEventCenter().notifyUser(msgInfo.get("username"), "New message from "
//				+ msgInfo.get("username"), msgInfo.get("body"));
		env.getEventCenter().notifyUser(mi);
		
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.byq.mm.engine.SmartStore#getMessageInfo(org.jivesoftware.smack.packet
	 * .Message)
	 */
	Map<String, String> getMessageInfo(Message msg) {
		/* Build the user id, username, resource */

		String userWithRes = msg.getFrom().toString(); // plain JabberID (width resource)
		int slash = userWithRes.lastIndexOf("/"); // select index of the
		// separator of Jabber ID
		// and resource
		String resource; // only the resource name
		String user; // only the Jabber id

		// Check if there was a separator (should always be) and assign the
		// proper values
		if (slash != -1) {
			resource = userWithRes.substring(slash + 1);
			user = userWithRes.substring(0, slash);
		} else {
			resource = "unknown";
			user = userWithRes;
		}

		String userName = user; // Alias, if there is one

		String body = msg.getBody(); // Message

		java.util.Date date = null; // getTimestamp(packet); currently not
		// working, so ignoring it and use the
		// current time.

		if (date == null) {
			date = new java.util.Date();
		}

		long time = date.getTime();

		HashMap<String, String> list = new HashMap<String, String>();
		list.put("user", user);
		list.put("resource", resource);
		list.put("username", userName);
		list.put("body", body);
		list.put("time", String.valueOf(time));

		return list;
	}

}
